package simorg.actions;

import simorg.actions.enrollment.EnrollmentJob;
import simorg.controller.UserController;
import simorg.domain.Course;
import simorg.domain.persistence.CourseTable;
import simorg.view.ModelView;
import simorg.view.WebSessionContext;

public class UserEnroll extends Action {

	public static String actionName = "enroll";
	public UserEnroll() {
		super(actionName);
		this.controllerName = UserController.controllerName;
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		String firstName = null, lastName = null, email = null;
		Course courseToEnroll = CourseTable.findById(wc.getDbConnection(), Integer.parseInt(wc.getRequestParameter("courseId")));
		
		if ( wc.hasReqeustParameter("email")) {
			email = wc.getRequestParameter("email");
		}
		if ( wc.hasReqeustParameter("firstName")) {
			firstName = wc.getRequestParameter("firstName");
		}
		if ( wc.hasReqeustParameter("lastName")) {
			lastName = wc.getRequestParameter("lastName");
		}
		
		EnrollmentJob job = new EnrollmentJob(courseToEnroll, firstName, lastName, email);
		job.enroll(wc);
		
		Action redirect = new CourseView(String.valueOf(courseToEnroll.getId()));
		wc.redirectAdmin(redirect, "enrollment");
		return null;
	}
	
	

}
